# -*- utf-8 -*-
# @Time: 2021/5/23 19:59
# @Author: CACode
import pymysql
from aestate.cacode.Factory import Factory

from aestate.util.Log import CACodeLog
from aestate.work import Manage
from aestate.work.Config import Conf
from aestate.work.SummerAdapter import LanguageAdapter


class MyAdapter(LanguageAdapter):

    def __init__(self):
        self.funcs = {
            'gt': self._gt_opera,
            'lt': self._lt_opera,
            'count': self._count_opera,
        }

        super(MyAdapter, self).__init__()

    def _gt_opera(self, instance, key, value):
        instance.args.append('`' + key + '`')
        instance.args.append(' > ')
        instance.args.append('%s')
        instance.args.append(' AND ')
        instance.params.append(value)

    def _lt_opera(self, instance, key, value):
        instance.args.append('`' + key + '`')
        instance.args.append(' < ')
        instance.args.append('%s')
        instance.args.append(' AND ')
        instance.params.append(value)

    def _count_opera(self, instance, key, value):
        instance.args.remove(instance.args[len(instance.args) - 1])
        as_cp = ''.join(instance.args)
        instance.args = []

        if '_ndist' not in key:
            instance.args.append(f'SELECT distinct a.{key},COUNT(*) AS {value} FROM ({as_cp}) as a')
        else:
            key = key.replace('_ndist', '', (key.count(' and ') - 1))
            instance.args.append(f'SELECT a.{key},COUNT(*) AS {value} FROM ({as_cp}) as a')


class BaseDataBase(Conf):
    def __init__(self):
        # 打印sql语句
        self.set_field('print_sql', True)
        # 返回最后一行的id
        self.set_field('last_id', True)

        super(BaseDataBase, self).__init__(
            host='localhost',
            port=3306,
            database='luntan',
            user='root',
            password='hu15879093053',
            creator=pymysql,
            adapter=MyAdapter()
        )


class BaseDatabaseConfig(Manage.Pojo):
    def __init__(self, **kwargs):
        # 设置日志对象
        kwargs['log_obj'] = CACodeLog(
            # 确认保存
            save_flag=True,
            # 保存位置
            path='/cacode/cacode.ren/blog_logs',
            # 日志最大100MB清除
            max_clear=100,
        )
        super(BaseDatabaseConfig, self).__init__(config_obj=BaseDataBase(), **kwargs)


class DatabaseTemplate(BaseDatabaseConfig):
    def __init__(self, **kwargs):
        self.id = Manage.tag.intField(auto_field=True, comment='自增主键')
        self.create_time = Manage.tag.datetimeField(
            auto_time=True, comment="创建时间")
        self.update_time = Manage.tag.datetimeField(
            update_auto_time=True, comment='更改时间')
        super(DatabaseTemplate, self).__init__(**kwargs)


class MyFactory(Factory):
    modules = {
        'article': 'tables.article.models',
        'user': 'tables.user.models',
    }
